//
//  TftpManager.m
//  TFTPDemo
//
//  Created by 陈冠杰 on 16/8/4.
//  Copyright © 2016年 EzioChen. All rights reserved.
//

#import "TftpManager.h"
#include "tftp.h"
#import <notify.h>

#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")



static TftpManager *ME;

static struct tftp_conn *tc_get;
static struct tftp_conn *tc_put;



@implementation TftpManager

+(id)sharedInstance{

    @synchronized ([TftpManager class]) {
        if (ME == nil) {
            ME = [[TftpManager alloc] init];
        }
    }
    return ME;
}


-(instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appOut:) name:UIApplicationDidEnterBackgroundNotification object:nil];
        
        CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL,
                                        screenLockStateChanged, NotificationLock, NULL,
                                        CFNotificationSuspensionBehaviorDrop);
    }
    return self;
}

-(void)appOut:(NSNotification*)note{
    tftp_interrupt(tc_get);
    tftp_interrupt(tc_put);
}


static void screenLockStateChanged(CFNotificationCenterRef center,
                                   void* observer,
                                   CFStringRef name,
                                   const void* object,
                                   CFDictionaryRef userInfo)
{
    NSString* lockstate = (__bridge NSString*)name;
    if ([lockstate isEqualToString:(__bridge  NSString*)NotificationLock]) {
        NSLog(@"locked.");
        tftp_interrupt(tc_get);
        tftp_interrupt(tc_put);
    } else {
        NSLog(@"lock state changed.");
    }
}



-(void)getHost:(NSString*)host Port:(int)port Remote:(NSString*)r_file Local:(NSString*)l_file{
    if (!host || !r_file || !l_file ) return;
    tc_get = tftp_connect(0, (char*)[r_file UTF8String], MODE_OCTET, (char*)[host UTF8String], port);
    tc_get->fw = fopen((char*)[l_file UTF8String], "wb");
    [self run_thread:tc_get];
}

-(void)putHost:(NSString*)host Port:(int)port Remote:(NSString*)r_file Local:(NSString*)l_file{
    if (!host || !r_file || !l_file ) return;
    tc_put = tftp_connect(1, (char*)[r_file UTF8String], MODE_OCTET, (char*)[host UTF8String], port);
    tc_put->fw = fopen((char*)[l_file UTF8String], "rb");
    [self run_thread:tc_put];
}



-(void)run_thread:(struct tftp_conn *)tc{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *file = [NSString stringWithUTF8String:tc->fname];
        int retval = tftp_transfer(tc);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (retval<0) {
                //NSLog(@"File transfer failed!");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TFTP_FAIL" object:file];
            }else if(retval == 0){
                //NSLog(@"File transfer OK.");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TFTP_OK" object:file];
            }
        });
        tftp_close(tc);
    });
}




@end
